// Learn TypeScript:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/typescript.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

const {ccclass, property} = cc._decorator;

import SpriteAnim from './08_sprite_anim';
import AnimConfig from './08_anim_config';
import Utils from '../Utils';

@ccclass
export default class NewClass extends cc.Component {

    @property(cc.Node)
    contentRoot: cc.Node = null;    

    @property(SpriteAnim)
    hero: SpriteAnim = null;

    @property(SpriteAnim)
    target: SpriteAnim = null;

    private _isSpelling:boolean = false;
    
    // LIFE-CYCLE CALLBACKS:

    onLoad () {

        Utils.removeItemToPool(this.contentRoot);
        var info = AnimConfig.getRoleInfo(this.hero.roleId);
        var index = 0;
        for(var k in info){
            if(k == 'attcak' || k.indexOf('spell') == 0){
                index++;
                var item = Utils.addItemFromPool(this.contentRoot);
                cc.loader.loadRes('icons/icon_spell' + index,cc.SpriteFrame,function(err,spriteFrame){
                    this.getComponent(cc.Sprite).spriteFrame = spriteFrame;
                }.bind(item));
                item.__meta = k;
            }
        }
    }

    onCastSpell(event){
        var animName = event.target.__meta;
        if(this._isSpelling){
            return;
        }
        this._isSpelling = true;
        var arr = [];
        arr.push(cc.spawn(cc.moveTo(0.3,this.target.node.position.sub(cc.v2(120,0))),cc.callFunc(function(){
            this.hero.playAnim('rush');
        },this)) );
        arr.push(cc.callFunc(function(){
            this.hero.playAnim(animName);
        },this));
        var animInfo = AnimConfig.getRoleInfo(this.hero.roleId)[animName];
        var playTime = animInfo.frames / animInfo.fps;
        arr.push(cc.delayTime(0.5 + playTime));
        arr.push(cc.moveTo(0.1,this.hero.node.position));
        arr.push(cc.callFunc(function(){
            this._isSpelling = false;
        },this));

        var act = cc.sequence(arr);
        this.hero.node.runAction(act);
    }

    start () {

    }

    // update (dt) {}
}
